<template>
  <view class="nurse-detail-page">
    <view class="page-header">
      <text class="page-title">护士详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button class="btn btn-primary" @click="handleEdit">编辑</button>
        <button v-if="nurse.is_active" class="btn btn-danger" @click="handleSetInactive">设为离职</button>
        <button v-else class="btn btn-success" @click="handleSetActive">设为在职</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">基本信息</text>
          <view :class="['status-badge', nurse.is_active ? 'status-active' : 'status-inactive']">
            {{ nurse.is_active ? '在职' : '离职' }}
          </view>
        </view>
        <view class="card-body">
          <view v-if="getImageUrl(nurse.photo)" class="detail-row vertical">
            <text class="label">工作照</text>
            <image 
              class="nurse-photo" 
              :src="getImageUrl(nurse.photo)" 
              mode="aspectFit"
              @click="previewImage(getImageUrl(nurse.photo))"
            />
          </view>
          
          <view class="detail-row">
            <text class="label">护士姓名</text>
            <text class="value highlight">{{ nurse.nurse_name || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">职称等级</text>
            <text class="value">{{ nurse.title_text || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">执业证号</text>
            <text class="value">{{ nurse.license_no || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">所属科室</text>
            <text class="value">{{ nurse.department || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">工作年限</text>
            <text class="value">{{ nurse.years_experience || 0 }}年</text>
          </view>
        </view>
      </view>
      
      <view v-if="nurse.user_info" class="detail-card">
        <view class="card-header">
          <text class="card-title">关联账户信息</text>
          <view :class="['status-badge', nurse.user_info.status === 0 ? 'status-active' : 'status-inactive']">
            {{ nurse.user_info.status === 0 ? '正常' : '禁用' }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">用户名</text>
            <text class="value">{{ nurse.user_info.username || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">昵称</text>
            <text class="value">{{ nurse.user_info.nickname || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">手机号</text>
            <text class="value">{{ nurse.user_info.mobile || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">真实姓名</text>
            <text class="value">{{ nurse.user_info.real_name || '未认证' }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(nurse.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(nurse.update_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const loading = ref(true)
const nurseId = ref('')
const nurse = reactive({
  _id: '',
  user_id: '',
  nurse_name: '',
  title_level: 0,
  title_text: '',
  license_no: '',
  department: '',
  years_experience: 0,
  is_active: true,
  photo: null,
  create_time: null,
  update_time: null,
  user_info: null
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  nurseId.value = currentPage.options.id || ''
  
  if (!nurseId.value) {
    uni.showToast({ title: '缺少护士ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/nurses/list' })
    }, 1500)
    return
  }
  
  await loadNurseData()
  loading.value = false
})

async function loadNurseData() {
  try {
    const dhNurses = uniCloud.importObject('dh-nurses')
    const result = await dhNurses.getNurseById(nurseId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(nurse, result.data)
    } else {
      throw new Error(result.message || '护士不存在')
    }
  } catch (err) {
    console.error('加载护士数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/nurses/list' })
    }, 1500)
  }
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function getImageUrl(imageData) {
  if (!imageData) return ''
  if (typeof imageData === 'string') return imageData
  if (typeof imageData === 'object' && imageData.url) return imageData.url
  if (Array.isArray(imageData) && imageData.length > 0) {
    const first = imageData[0]
    return typeof first === 'string' ? first : (first.url || '')
  }
  return ''
}

function previewImage(url) {
  if (!url) return
  uni.previewImage({
    urls: [url],
    current: url
  })
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/nurses/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/nurses/edit?id=${nurseId.value}` })
}

function handleSetInactive() {
  uni.showModal({
    title: '确认离职',
    content: '确定要将该护士设置为离职状态吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '操作中...' })
          const dhNurses = uniCloud.importObject('dh-nurses')
          const result = await dhNurses.updateNurse(nurseId.value, {
            is_active: false
          })
          uni.hideLoading()
          
          if (result.code === 200) {
            uni.showToast({ title: '已设为离职', icon: 'success' })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/business/nurses/list' })
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '操作失败', icon: 'none' })
          }
        } catch (err) {
          console.error('操作失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '操作失败', icon: 'none' })
        }
      }
    }
  })
}

function handleSetActive() {
  uni.showModal({
    title: '确认在职',
    content: '确定要将该护士设置为在职状态吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '操作中...' })
          const dhNurses = uniCloud.importObject('dh-nurses')
          const result = await dhNurses.updateNurse(nurseId.value, {
            is_active: true
          })
          uni.hideLoading()
          
          if (result.code === 200) {
            uni.showToast({ title: '已设为在职', icon: 'success' })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/business/nurses/list' })
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '操作失败', icon: 'none' })
          }
        } catch (err) {
          console.error('操作失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '操作失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.nurse-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
  
  &.btn-success {
    background: #34c759;
    color: #fff;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-active {
    background: #e8f5e9;
    color: #2e7d32;
  }
  
  &.status-inactive {
    background: #ffebee;
    color: #c62828;
  }
}

.card-body {
  padding: 32rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.vertical {
    flex-direction: column;
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
  margin-bottom: 8rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
  
  &.highlight {
    font-weight: bold;
    color: #007aff;
  }
}

.nurse-photo {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  margin-top: 16rpx;
}
</style>

